package com.example.auth.controller;

import com.alibaba.fastjson.JSON;
import com.example.auth.clients.UserFeignClient;
import com.example.auth.constants.CommonConstants;
import com.example.auth.model.Result;
import com.example.auth.model.SysClient;
import com.example.auth.model.User;
import com.example.auth.service.ClientService;
import com.example.auth.utils.JwtUtil;
import com.example.auth.utils.ResultUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangtao on 2018/3/3.
 */
@RestController
public class AuthController {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private ClientService clientService;

    /**
     * 用户名/密码授权模式
     *
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping("/login")
    public Result login(@RequestBody Map map) throws Exception {
        String username = String.valueOf(map.get("userLoginName"));
        String password = DigestUtils.md5Hex(String.valueOf(map.get("password")));
        Result result = userFeignClient.checkLogin(username, password);
        if (!result.getCode().equals(CommonConstants.SUCCESS)) {
            return result;
        }
        Map<String, Object> params = new HashMap<String, Object>(2);
        User user = JSON.parseObject(JSON.toJSONString(result.getData()), User.class);
        if (user != null) {
            // 用户校验成功后生成token
            params.put("token", jwtUtil.generateTokenByUser(user));
            params.put("menus", userFeignClient.menus(user.getId()));
            params.put("buttons", userFeignClient.allButtons(user.getId()).getData());
        }
        return ResultUtil.success(user, params);
    }

    @PostMapping("/getToken")
    public Result getToken(@RequestBody User user) throws Exception {
        Result result = userFeignClient.checkLogin(user.getUsername(), user.getPassword());
        if (!result.getCode().equals(CommonConstants.SUCCESS)) {
            return result;
        }
        Map<String, Object> params = new HashMap<>(2);
        user = JSON.parseObject(JSON.toJSONString(result.getData()), User.class);
        if(user != null){
            params.put("token", jwtUtil.generateTokenByUser(user));
            params.put("expired", jwtUtil.getExpired());
        }
        return ResultUtil.success(params);
    }

    /**
     * 服务授权模式
     *
     * @return
     */
    @PostMapping("/authorize")
    public Result authorized(@RequestParam("name") String name, @RequestParam("secret") String secret) throws Exception {
        Result result = new Result();
        if (StringUtils.isBlank(name) || StringUtils.isBlank(secret)) {
            return ResultUtil.fail("请求参数不合法", CommonConstants.EX_PARAM_ILLEGAL_CODE);
        }
        SysClient client = clientService.findByCode(name);
        if (client == null || client.getSecret() == null) {
            return ResultUtil.fail("没有访问权限", CommonConstants.EX_NO_SERVICE_ACCESS_CODE);
        }
        String sign = DigestUtils.md5Hex(name + client.getSecret()).toUpperCase();
        // 校验密文
        if (secret.equals(sign)) {
            // 授权
            String token = jwtUtil.generateTokenByClient(client);
            result.setCode(CommonConstants.SUCCESS);
            result.setMsg("授权通过");
            result.setData(token);
        } else {
            result.setCode(CommonConstants.FAILURE);
            result.setMsg("签名错误");
        }
        return result;
    }

    /**
     * 获取指定服务权限列表
     *
     * @return
     * @param clientId
     */
    @PostMapping("/getServiceList")
    public Result getServiceList(@RequestParam Long clientId) {
        List<String> allService = clientService.findAllService(clientId);
        if (allService == null) {
            allService = new ArrayList<String>();
        }
        return ResultUtil.success(allService);
    }

    @GetMapping("/searchPatient")
    public Result searchPatient(@RequestParam String medicalNumber){
        Result r = userFeignClient.findByMedicalNumber(medicalNumber);
        if(r.getData() == null){
            return ResultUtil.fail("未查询到患者信息");
        }
        return r;
    }

}
